/**
 * 房间管理
 * @constructor
 */
function Room() {
}

Room.init = function () {

    let Image = false;
    let Delete = false;
    let Update = false;
    //查询当前角色具备的菜单功能权限
    $.ajax({
        url: "/room/getPermission",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $.each(data,function (i,button) {
                if (button.enDesc == "Insert"){
                    $("#toolbar").css("display","block");
                }
                if (button.enDesc == "Image"){
                    Image = true;
                }
                if (button.enDesc == "Delete"){
                    Delete = true;
                }
                if (button.enDesc == "Update"){
                    Update = true;
                }
            });
        },
        error: function () {
            // alert("Error");
        }
    });

    bindShopForRoleselect();
    bindShopForRoleselect2();
    $('#tableList').bootstrapTable({
        url: '/room/tableSearch',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: true,
        showRefresh: true,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
                id: $('#search_roomName').val(), // 请求时向服务端传递的参数
                state: $('#search_State').val(),
                shopId: $('#search_shopName').val(),
            };
            return query_params;
        },
        columns: [
            {
                //field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            { field: 'shopName', title: '商铺名称',align: 'center'},
            { field: 'name', title: '房间名称',align: 'center'},
            {
                field: 'url', title: '房间图片',align: 'center',width: 200,
                formatter:function(value){
                    return "<img src=\""+value+"\" class=\"img-responsive\">";
                }
            },
            { field: 'roomType', title: '房间类型',align: 'center'},
            { field: 'price', title: '单价',align: 'center'},
            { field: 'space', title: '房间大小(平方)',align: 'center'},
            {
                title: '推荐人数',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml =row.minPerson+ " -- "+row.maxPerson;
                    return optionHtml;

                }
            },
            {
                title: '状态',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if(row.state==0)
                    {
                        optionHtml="不可用";
                    }
                    else {
                        optionHtml="可用";
                    }
                    return optionHtml;
                }
            },
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (Image){
                        optionHtml += "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"image\")' title=\"图片\" ><i class=\"fa fa-edit\"></i>图片</a>";
                    }
                    if (Update){
                        optionHtml =optionHtml+ " <a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                    }
                    /*if (Delete){
                        optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"delete\")'  title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>"
                    }*/

                    return optionHtml;

                }
            }
        ]
    });
}
//查询方法****************************
function doSearch() {
    $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
}
//重置****************************
function doRest() {
    $("#search_roomName").val("");
    $("#search_State").val("");
    $("#search_shopName").val("");
    $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
}
//增加方法****************************
var Action="";
var Id=0;
var roomId=0;
var pxt="/room"; //控制器名称


function addRecord() {
    Id=0;
    Action="add";
    $("#myform")[0].reset();
    $("#save").removeAttr("disabled");
    $("#text_ClientNo").removeAttr("readonly");

}
//增加/修改数据保存****************************
function saveRecord() {
    //创建传递的参数
    var postdata = {
        id: Id,
        action:Action,
        name: $("#text_Name").val(),
        shopId: $("#com_ShopId").val(),
        price: $("#text_Price").val(),
        minPerson: $("#text_MinPerson").val(),
        maxPerson: $("#text_MaxPerson").val(),
        topic: $("#text_Topic").val(),
        state: $("#com_State").val(),
        isMeter: $("#com_IsMeter").val(),
        roomType: $("#text_RoomType").val(),
        instructions: $("#text_Instructions").val(),
        space:$("#text_Space").val(),
    };
    // console.log(JSON.stringify(postdata));
    //发送异步请求到后台保存用户数据
    $.ajax({
        url:pxt+"/save",
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data,type) {
    if(type=="edit")
    {
        //修改
        Id=data.id;
        Action="edit";
        //  $("#text_ClientNo").attr("readonly", "true");
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    }
    else if(type=="image")
    {
        //修改
        Id=data.id;
        Action="image";
        //  $("#text_ClientNo").attr("readonly", "true");
        $("#myform2")[0].reset();
       // $("#save").removeAttr("disabled");
        $("#roomUrl1").removeAttr("src");
        $("#roomUrl2").removeAttr("src");
        $("#roomUrl3").removeAttr("src");
        getImage();
        $('#myModalAdd2').modal('show')
    }
    else if(type=="delete")
    {
        //删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            //点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt+"/deleteById/"+data.id,
                dataType : "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("删除成功!", "请继续操作", "success");
                    }
                    else{
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    }
    else if(type=="change")
    {
        //状态变更
        var alertstr = "未知操作";
        var state = 0;
        if (data.state == 0)
        {
            alertstr = "是否将该用户变更为：激活？";
            state = 1;
        }
        else if (data.state == 1) {
            alertstr = "是否将该用户变更为：未激活？";
            state = 0;
        }
        swal({
            title: "状态变更",
            text: alertstr,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            //点击删除之后此处进行传递后台
            //创建传递的参数
            var postdata = {
                action:"change",
                id: data.id,
                state:state,
            };
            $.ajax({
                url:pxt+"/save",
                type:"post",
                data:JSON.stringify(postdata),
                contentType:"application/json",
                dataType:"json",
                success:function(data){
                    if (data.code === "200") {
                        $('#myModalAdd').modal('hide')
                        doSearch();
                        swal("状态已变更!", "请继续操作", "success");
                    } else {
                        swal("操作失败!", "请重试", "error");
                    }
                }
            })

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#text_Name").val(data.name);
    $("#com_ShopId").val(data.shopId);
    $("#text_Price").val(data.price);
    $("#text_MinPerson").val(data.minPerson);
    $("#text_MaxPerson").val(data.maxPerson);
    $("#text_Topic").val(data.topic);
    $("#com_State").val(data.state);
    $("#com_IsMeter").val(data.isMeter);
    $("#text_RoomType").val(data.roomType);
    $("#text_Instructions").val(data.instructions);
    $("#text_Space").val(data.space);
}
//绑定下拉****************************
function bindUsersRoleselect() {

    $.ajax({
        url: "/room/getShopForRole",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#com_ShopId");
            //删除节点
            $("#com_ShopId option").remove();

            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属用户--").val("");

            ddl1.append(opt1);

            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].name).val(result[key].id);

                ddl1.append(opt1);

            });
        },
        error: function () {
            // alert("Error");
        }
    });

}
//上传****************************
function ImportShipmentStatusList() {
    var timestamp = new Date().getTime();
    var upname = "fuImportMultipleShipmentStatus";
    console.log(timestamp);
    console.log("upname:"+$("#" + upname).val());
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: '/room/uploadImages?type=2&id='+Id,
        secureuri: false,
        fileElementId: upname,
        dataType: 'text',
        success: function (data, status) {
           // $("#photourl").attr("src", "/images/" + data);
           // $("#imgURL").attr("value", data);
            getImage();
        },
        error: function (data, status, e) {
            alert("上传失败");
        }

    });
}

function getImage() {
    $("#divform").html("");
    var html="";
    $.ajax({
        url:pxt+"/getRoomImages?type=2&roomId="+Id,
        type:"get",
        //data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data) {
            console.log(data);
            $.each(data, function (i, val) { //两个参数，第一个参数表示遍历的数组的下标，第二个参数表示下标对应的值
                console.log(i + '```````' + val.url);
                var n=i+1;
                html="";
                html=html+"<div class=\"row\">";
                html=html+"<label class=\"col-lg-3 control-label\">图片"+n+"</label>";
                html=html+"<div class=\"col-lg-9\">";
                html=html+"<div class=\"form-group\" style='width:420px; height:250px'>";
                html=html+"<img style='width:420px; height:250px' src=\"/images/"+val.url+"\" />";
                html=html+"<span class=\"label label-danger pull-right\" style=\"cursor:pointer\" onclick=\"delimage("+val.id+");\">删除</span>";
                html=html+"</div>";
                html=html+"</div>";
                html=html+"</div>";
                $("#divform").append(html);
            });


        }
    });
}
function delimage(id) {

        //删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该图片？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            //点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt+"/deleteImageById/"+id,
                dataType : "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        getImage();
                        swal("删除成功!", "请继续操作", "success");
                    }
                    else{
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });



}
//绑定下拉****************************
function bindShopForRoleselect() {

    $.ajax({
        url: "/room/getShopForRole",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#com_ShopId");
            //删除节点
            $("#com_ShopId option").remove();

            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属商铺--").val("");

            ddl1.append(opt1);

            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].name).val(result[key].id);

                ddl1.append(opt1);

            });
        },
        error: function () {
            // alert("Error");
        }
    });

}

//绑定下拉****************************
function bindShopForRoleselect2() {

    $.ajax({
        url: "/room/getShopForRole",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#search_shopName");
            //删除节点
            $("#search_shopName option").remove();

            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属商铺--").val("");

            ddl1.append(opt1);

            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].name).val(result[key].id);

                ddl1.append(opt1);

            });
        },
        error: function () {
            // alert("Error");
        }
    });

}
//绑定下拉****************************
function bindShopForRoleselect3() {

    $.ajax({
        url: "/room/getRoomName/"+$("#search_shopName").val(),
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#search_roomName");
            //删除节点
            $("#search_roomName option").remove();

            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属房间--").val("");

            ddl1.append(opt1);
            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].name).val(result[key].id);
                ddl1.append(opt1);

            });
        },
        error: function () {
            // alert("Error");
        }
    });

}